package fr.nekloth.android.hinode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class SelectToneActivity extends Activity {

	public Context theContext;
	int initialStreamVolume = 0;
	int initialSystemStreamVolume = 0;
	
	MediaPlayer myPlayer = new MediaPlayer();
	
	Button btnTest;
	Button btnOk;
	Button btnCancel;
	Spinner spToneList, spVolume;
	
	int mode = Activity.MODE_PRIVATE;
	
	SharedPreferences mySharedPreferences;
	
	String selectedTone_path;
	int    selectedTone_volume;
	
	private Cursor musicCursor;
	private int musicCount;
	
	public static String KEY_MP3FILE_PREFERENCE = "MP3File_tone";
	public static String KEY_VOLUME_PREFERENCE  = "MP3File_volume";

    protected void toastLongInfo(String theMessage) {
    	Toast.makeText(this, theMessage,Toast.LENGTH_LONG).show();
    }

    protected void toastShortInfo(String theMessage) {
    	Toast.makeText(this, theMessage,Toast.LENGTH_SHORT).show();
    }

	
	public void loadTonePreferences(){
		try {
			mySharedPreferences = getSharedPreferences(applicationStartup.MYPREFS, mode);
			selectedTone_path = mySharedPreferences.getString(KEY_MP3FILE_PREFERENCE, "");
			selectedTone_volume = mySharedPreferences.getInt(KEY_VOLUME_PREFERENCE, alarmReceiverDisplay.MENU_VOLUME_MEDIUM);
		} catch (Exception e) {
			// Exception
		}
	}
	
	public void saveTonePreferences() {
    	try {
	    	/* Preparation of the save preferences informations */
	    	mySharedPreferences = getSharedPreferences(applicationStartup.MYPREFS,mode);
	    	SharedPreferences.Editor editor = mySharedPreferences.edit();
	    	editor.putString(KEY_MP3FILE_PREFERENCE, selectedTone_path);
	    	editor.putInt(KEY_VOLUME_PREFERENCE, selectedTone_volume);
	    	editor.commit();
    	} catch (Exception e) {
    		//Exception
    	}
	}

	
	
	public void setDisplay() {
		   setContentView(R.layout.select_tone);
      
	       //Blur the background
	       getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
	       
	       // SET SPINNER data
	       ArrayAdapter<CharSequence> m_adapterForSpinner;
	       spToneList = (Spinner) findViewById(R.id.spToneList);
	       m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item); 
	       m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	       spToneList.setAdapter(m_adapterForSpinner);

	       m_adapterForSpinner.add((String)getText(R.string.selecttone_default_sound));
	       
	        //NEW v1.0 : retrieve MEDIA LIST
	        String[] proj = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION};
	        this.musicCursor = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);

	        if(this.musicCursor!=null && this.musicCursor.getCount()!=0){
	            this.musicCount = musicCursor.getCount();
	            toastShortInfo("" + musicCount + " " + (String)getText(R.string.x_music_files_found));
	        } else {
	        	Log.d("Nekloth", "No music files found");
	        	//toastLongInfo("No music files found.\nAre you sure you have some ?\nIs the SDCard mounted ?");
	        	toastLongInfo(""+(String)getText(R.string.no_music_files_found));
	        } 
	       
	        
	      //NEW v1.0 : Add info into spinner AND identify those to SELECT
	        int indexToSelect = 0;
	        for (int i = 0; i < musicCount; i++) {
	        	musicCursor.moveToPosition(i);
	        	//Log.d("Nekloth", "" + musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
	        	m_adapterForSpinner.add("" + (i+1) + ". " + musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
	        	if (musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)).compareToIgnoreCase(selectedTone_path) == 0) {
	        		Log.d("Nekloth",musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)) + " == " + selectedTone_path);
	        		indexToSelect = i + 1;
	        		Log.d("Nekloth","Index : "+indexToSelect);
	        	} else {
	        		//Log.d("Nekloth",musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)) + " <> " + selectedTone_path);
	        	}
	        }
	        spToneList.setSelection(indexToSelect);
	        
	        Log.d("Nekloth","-= End DEV METHOD");
	       //-------------------------------------------------------------
	       
	       
	       
	       
	       spVolume = (Spinner) findViewById(R.id.spVolumeList);
	       ArrayAdapter adapterRelative = ArrayAdapter.createFromResource( this, R.array.tuneVolume, android.R.layout.simple_spinner_item); 
	       adapterRelative.setDropDownViewResource(android.R.layout.select_dialog_item);
	       spVolume.setAdapter(adapterRelative);

	       //Select appropriate line for MUSIC
	       spVolume.setSelection(1);
	       switch (selectedTone_volume) {
	       		case alarmReceiverDisplay.MENU_VOLUME_SILENCE: spVolume.setSelection(0);break;
	       		case alarmReceiverDisplay.MENU_VOLUME_LOW: spVolume.setSelection(1);break;
	       		case alarmReceiverDisplay.MENU_VOLUME_MEDIUM: spVolume.setSelection(2);break;
	       		case alarmReceiverDisplay.MENU_VOLUME_HIGH: spVolume.setSelection(3);break;
	       }
	       
	       
	       //Set LISTENERS
	       btnCancel = (Button) findViewById(R.id.tone_btnCancel);
	       btnCancel.setOnClickListener(new OnClickListener () {
				@Override
				public void onClick(View arg0) {
					if (myPlayer.isPlaying()) myPlayer.stop();
					finish();
					Log.d("Nekloth", "Click on CANCEL");
					// TO BE CONFIRMED !!!!!!!!!!
				}
	       });
	       
	       btnOk = (Button) findViewById(R.id.tone_btnOk);
	       btnOk.setOnClickListener(new OnClickListener () {
				@Override
				public void onClick(View arg0) {
					if (myPlayer.isPlaying()) myPlayer.stop();
					
					if (spToneList.getSelectedItemPosition() != 0) {
						musicCursor.moveToPosition(spToneList.getSelectedItemPosition()-1);
						selectedTone_path = musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
					} else {
						selectedTone_path = "";
					}

					switch (spVolume.getSelectedItemPosition()) {
						case 0: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_SILENCE;break;
						case 1: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_LOW;break;
						case 2: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_MEDIUM;break;
						case 3: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_HIGH;break;
					}
					saveTonePreferences();
					finish();
				}
	       });

	       
	       btnTest = (Button) findViewById(R.id.tone_btnTest);
	       btnTest.setOnClickListener(new OnClickListener () {
				@Override
				public void onClick(View arg0) {
					if (myPlayer!=null && myPlayer.isPlaying()) {
						Log.d("Nekloth","MP is playing : Stop the music");
						stopMusicPlaying();
					} else {
						Log.d("Nekloth","MP is NOT playing : PLAY the music");
						startMusicPlaying();
					}
				}
	       });
	       
	       Typeface face=Typeface.createFromAsset(getAssets(), applicationStartup.GLOBAL_FONT_TO_USE);
	       TextView tv=(TextView)findViewById(R.id.select_tone_title);
	       tv.setTypeface(face);
	       
	       tv.setText(R.string.selecttone_title);
	}
	
	public void stopMusicPlaying() {
	    myPlayer.stop();	
	    myPlayer.reset();
		spToneList.setEnabled(true);
		spVolume.setEnabled(true);
		btnTest.setText((String)getText(R.string.selecttone_test_the_tone_start));		
	}

	public void startMusicPlaying() {
	    spToneList.setEnabled(false);
		spVolume.setEnabled(false);
		
		switch (spVolume.getSelectedItemPosition()) {
			case 0: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_SILENCE;break;
			case 1: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_LOW;break;
			case 2: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_MEDIUM;break;
			case 3: selectedTone_volume = alarmReceiverDisplay.MENU_VOLUME_HIGH;break;
		}
		
		if (spToneList.getSelectedItemPosition() != 0) {
			musicCursor.moveToPosition(spToneList.getSelectedItemPosition()-1);
			selectedTone_path = musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
			playSoundFile(musicCursor.getString(musicCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));			
		} else {
			playSoundFile(null);
		}
		
		btnTest.setText((String)getText(R.string.selecttone_test_the_tone_stop));						
	}
	
	private boolean backupVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
			initialStreamVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
			initialSystemStreamVolume = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
			done = true;
		} catch (Exception e) {
			applicationStartup.toastInfo(this,"Initialisation error (" + e.getMessage() + ")");
		}
		return done;
	}
	
	private boolean restoreVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);
			am.setStreamVolume(AudioManager.STREAM_MUSIC, initialStreamVolume, 0);
			am.setStreamVolume(AudioManager.STREAM_SYSTEM, initialSystemStreamVolume, 0);
			done = true;
		} catch (Exception e) {
			applicationStartup.toastInfo(this,"Restore error (" + e.getMessage() + ")");
		}
		return done;
	}
	
	public void playSoundFile(String pathToMP3File) {
		 
		  backupVolumeSettings();

		  float theVolume = 0.05f;
		  AudioManager am;
		  
		  //Retrieve volume level
	  	  switch (selectedTone_volume) {
	  	  	case applicationStartup.MENU_VOLUME_SILENCE: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_SILENCE_LEVEL;break;
	  	  	case applicationStartup.MENU_VOLUME_LOW: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_LOW_LEVEL;break;
	  	  	case applicationStartup.MENU_VOLUME_MEDIUM: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL;break;
	  	  	case applicationStartup.MENU_VOLUME_HIGH: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_HIGH_LEVEL;break;
	  	  }	
	  	  
			//- PLAY SOUND --------------------------------------------------------------------------------
			try {
				try {
					Log.d("Nekloth","MediaPlayer : Try to set DataSource to " + pathToMP3File);
				    myPlayer.reset();
				    myPlayer.setDataSource(pathToMP3File);
				    Log.d("Nekloth","MediaPlayer : DataSource Set to " + pathToMP3File);
				    myPlayer.prepare();
			    } catch (Exception e) {
				    Log.d("Nekloth","MediaPlayer : DataSource Set failed. Default sound " + pathToMP3File);
				    Log.d("Nekloth","MediaPlayer Exception : " + e.getMessage() + "-" + e.getCause() );
			    	myPlayer = MediaPlayer.create(this, R.raw.pop);
			    }
			    
		        myPlayer.setScreenOnWhilePlaying(true);
		        myPlayer.setAudioStreamType(alarmReceiverDisplay.STREAM_TO_USE);
		        am = (AudioManager) this.getSystemService(this.AUDIO_SERVICE);	
		        am.setStreamVolume(alarmReceiverDisplay.STREAM_TO_USE, am.getStreamMaxVolume(alarmReceiverDisplay.STREAM_TO_USE), 0);
		        //myPlayer.setVolume(alarmReceiverDisplay.MUSIC_VOLUME_LOW_LEVEL, alarmReceiverDisplay.MUSIC_VOLUME_LOW_LEVEL);
		        Log.d("Nekloth","Selected : " + selectedTone_volume);
		        Log.d("Nekloth","Volume used : " + theVolume);
		        myPlayer.setVolume(theVolume, theVolume);
		        myPlayer.start();
		        myPlayer.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						stopMusicPlaying();
						restoreVolumeSettings();
						mp.reset();
					}
				});
			
			} catch (Exception e) {
				applicationStartup.toastInfo(this, "Music exception: " + e.getMessage());
			}
		}

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        theContext = this;
        
        loadTonePreferences();
        setDisplay();
    }
    

	
}
